package cn.bugDance.trigger.listener;

import cn.bugDance.domain.award.model.entity.DistributeAwardEntity;
import cn.bugDance.domain.award.model.valobj.SendAwardVO;
import cn.bugDance.domain.award.service.IAwardService;
import cn.bugDance.types.exception.AppException;
import cn.bugDance.types.response.BaseEvent;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
@RocketMQMessageListener(topic = "sendUserAwardTopic", consumerGroup = "send-award-consumer-group")
public class SendAwardListener implements RocketMQListener<String> {

    @Resource
    private IAwardService awardService;

    @Override
    public void onMessage(String s) {
        try{
            BaseEvent<SendAwardVO> message = JSON.parseObject(s, new TypeReference<BaseEvent<SendAwardVO>>(){});
            log.info("【发奖MQ监听器-SendAwardListener】抽奖发奖MQ结果: {}", JSON.toJSONString(message));

            SendAwardVO sendAwardVO = message.getData();
            DistributeAwardEntity distributeAwardEntity = new DistributeAwardEntity();
            distributeAwardEntity.setAwardId(sendAwardVO.getAwardId());
            distributeAwardEntity.setUserId(sendAwardVO.getUserId());
            distributeAwardEntity.setAwardKey(sendAwardVO.getAwardKey());
            distributeAwardEntity.setAwardConfig(sendAwardVO.getAwardConfig());
            distributeAwardEntity.setOrderId(sendAwardVO.getOrderId());

            awardService.distributeAward(distributeAwardEntity);
            log.info("【发奖MQ监听器-SendAwardListener】发奖成功");
        }catch (AppException e){
            log.error("【发奖MQ监听器-SendAwardListener】抽奖发奖MQ异常, msg: {}", e.getInfo());
            return;
        }catch (Exception e){
            log.error("【发奖MQ监听器-SendAwardListener】抽奖发奖MQ失败");
            throw e;
        }
    }
}
